<?php
namespace app\middleware;

use think\facade\Config;
use think\facade\Request;
use think\Response;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;

class JwtAuth
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取token
        $token = $this->getToken($request);
        
        if (!$token) {
            return Response::create(['code' => 401, 'msg' => '未登录或TOKEN已过期'], 'json', 401);
        }
        
        // 验证token
        try {
            $key = Config::get('jwt.secret_key');
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            
            // 将用户ID保存到请求对象中，方便后续使用
            $request->userId = $decoded->data->user_id;
            
            return $next($request);
        } catch (ExpiredException $e) {
            return Response::create(['code' => 401, 'msg' => 'TOKEN已过期'], 'json', 401);
        } catch (SignatureInvalidException $e) {
            return Response::create(['code' => 401, 'msg' => 'TOKEN签名错误'], 'json', 401);
        } catch (\Exception $e) {
            return Response::create(['code' => 401, 'msg' => 'TOKEN验证失败: ' . $e->getMessage()], 'json', 401);
        }
    }
    
    /**
     * 获取请求中的token
     * @param \think\Request $request
     * @return string|null
     */
    protected function getToken($request)
    {
        $token = $request->header('Authorization');

        if (!$token) {
            return null;
        }
        
        // 通常Authorization头部的内容格式为 "Bearer token字符串"
        if (strpos($token, 'Bearer ') !== false) {
            $token = str_replace('Bearer ', '', $token);
        }
        
        return $token;
    }
} 